'''
Created on Aug 21, 2012

@author: pedro
'''
import ConfigParser
import os
import tarfile
import csv
import numpy as np

from Plotting import save_to_heatmap, avg_output_bar_graph
from Utils import ttest_ind
from Preprocessor import save_battery_to_file

def get_config_params(config_file):
    config = ConfigParser.RawConfigParser(allow_no_value=False)
    config.readfp(open(config_file))
    
    config_params = {}
    
    config_params["multithreading"]     = config.getboolean("heimdallpy", "multithreading")
    config_params["profiling"]          = config.getboolean("heimdallpy", "profiling")
    config_params["num_iterations"]     = config.getint("heimdallpy","num_iterations")
    
    config_params["num_hdrs"]           = config.getint("heimdallpy", "num_hdrs")
    config_params["num_pplus_hdrs"]     = config.getint("heimdallpy", "num_pplus_hdrs")
    config_params["num_regular_trials"] = config.getint("heimdallpy", "num_regular_trials")
    config_params["num_extra_trials"]   = config.getint("heimdallpy", "num_extra_trials")
    
    config_params["usigmoid_intercept"]     = config.getfloat("hdr_gen", "usigmoid_intercept")
    config_params["usigmoid_slope"]         = config.getfloat("hdr_gen", "usigmoid_slope")
    config_params["usigmoid_gaussian_mu"]   = config.getfloat("hdr_gen", "usigmoid_gaussian_mu")
    config_params["usigmoid_gaussian_sigma"] = config.getfloat("hdr_gen", "usigmoid_gaussian_sigma")
    
    config_params["time"]    =    config.getint("neuron_phys", "time")
    config_params["dt"]      =    config.getfloat("neuron_phys", "dt")
    config_params["numPyrs"] =    config.getint("neuron_phys", "numPyrs")
    config_params["v0"]      =    config.getfloat("neuron_phys","v0")
    config_params["Rm"]      =    config.getfloat("neuron_phys","Rm")
    config_params["Cm"]      =    config.getfloat("neuron_phys","Cm")
    config_params["tau_ref"] =    config.getfloat("neuron_phys","tau_ref")
    config_params["Vth"]     =    config.getfloat("neuron_phys","Vth")
    config_params["V_spike"] =    config.getfloat("neuron_phys","V_spike")
    config_params["oscillator_freq"] = config.getfloat("neuron_phys", "oscillator_freq")
    
    config_params["stdp_decay_factor"]   = config.getfloat("output_layer","stdp_decay_factor")
    config_params["max_weight"]          = config.getfloat("output_layer","max_weight")
    config_params["connectivity"]        = config.getfloat("output_layer","connectivity")
    
    config_params["Aplus"]   = config.getfloat("stdp","Aplus")
    config_params["Aminus"]  = config.getfloat("stdp","Aminus")
    
    config_params["stdp_tauplus"]    = config.getfloat("stdp","stdp_tauplus")
    config_params["stdp_tauminus"]   = config.getfloat("stdp", "stdp_tauminus")
    
    config_params["time_stop"] = config.getint("integrate","time_stop")
    
    return config_params


def get_average_hdr_heatmap():
    hdr_bat_data = []
    dirList=os.listdir(os.getcwd())
    for fname in dirList:
        if fname.startswith('hdr_bat_'): #TODO: Change pattern-matching to variable
            hdr_bat_data.append(np.genfromtxt(fname))
            os.remove(fname)
    
    summed_matrix = (1.0/len(hdr_bat_data)) * reduce(lambda a, b: np.add(a,b), hdr_bat_data)
    save_to_heatmap(summed_matrix, "hdr_average_heatmap.png") #TODO: Automate naming


def log_cleanup():
    tfilename = "Logs.tar.bz2" #TODO: Change to specify run time start/trial #
    tar = tarfile.open(tfilename, "w:bz2")
    for files in os.listdir("."):
        if files.endswith(".log"):
            tar.add(files)
            os.remove(files)
    tar.close()
    if tarfile.is_tarfile(tfilename):
        print "%s is a valid tar file" % tfilename
    else:
        print "%s is not a valid tar file" % tfilename
    return


'''
Always of the CSV format: bminus, bplus, pminus, pplus
'''
def write_to_output_file(data, datafile):
    with open(datafile, "a") as myfile:
        for item in data:
            myfile.write("{0},{1},{2},{3},{4}\n".format(item[0],item[1],item[2],item[3],item[4]))
    return


def calculate_results_from_output(data_filename):
    bminus = []
    bplus = []
    pminus = []
    pplus = []
    
    datafile = open(data_filename, 'rb')
    
    ''' Step 1: Segregate Output Based on Control/Experimental Group '''
    csvReader = csv.reader(datafile, delimiter=',')
    for row in csvReader:
        if float(row[0]) == 0:
            bminus.append(float(row[2]))
            bplus.append(float(row[3]))
        else:
            pminus.append(float(row[2])) 
            pplus.append(float(row[3]))
            
    datafile.close()
    
    ''' Step 2: Test for Significant Differences Using T-Test '''
    
    bb_ttest, bb_pstat = ttest_ind(bminus, bplus, 0, False)
    pp_ttest, pp_pstat = ttest_ind(pminus, pplus, 0, False)
    
    print "T-Test Statistic(s) and P-Value(s) for B-/B+: ",bb_pstat
    
    print "T-Test Statistic(s) and P-Value(s) for P-/P+: ",pp_pstat
    
    avg_output_bar_graph(bminus,bplus,pminus,pplus,bb_pstat,pp_pstat,"results_chart.png")
    